package com.ningjingjing.api;


import com.ningjingjing.model.Album;
import com.ningjingjing.model.User;
import com.ningjingjing.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/my-album-list.json")
public class MyAlbumListApi extends AbsApiServlet {
    @Override
    protected Object doGetInner(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, APIException {
        User currentUser = (User)req.getSession().getAttribute("currentUser");
        if (currentUser == null) {
            throw new APIException("用户必须首先进行登录");
        }

        List<Album> albumList = new ArrayList<>();
        try (Connection c = DBUtil.getConnection()) {
            String sql;
            sql = "SELECT aid, name, cover, count FROM album WHERE uid = ? ORDER BY aid DESC";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setInt(1, currentUser.uid);
                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {
                        Album album = new Album();
                        album.aid = rs.getInt("aid");
                        album.name = rs.getString("name");
                        album.cover = rs.getString("cover");
                        album.count = rs.getInt("count");

                        albumList.add(album);
                    }
                }
            }
        }

        return albumList;
    }
}
